<?php

namespace seecms;

use magein\utils\Variable;
use seecms\develop\config\DevelopConfig;
use seecms\lib\config\BackupConfig;
use seecms\lib\config\CacheConfig;
use seecms\lib\config\DatabaseConfig;
use seecms\lib\config\LangConfig;
use seecms\lib\config\MessageConfig;
use seecms\lib\config\PageConfig;
use seecms\lib\config\PermissionConfig;
use seecms\lib\config\ProviderConfig;
use seecms\lib\config\RightToolbarConfig;
use seecms\lib\config\TwigConfig;
use seecms\lib\config\UploadConfig;
use seecms\lib\config\VendorConfig;

/**
 * 配置使用单列模式
 * @property BackupConfig $backup
 * @property CacheConfig $cache
 * @property DatabaseConfig $database
 * @property ProviderConfig $provider
 * @property LangConfig $lang
 * @property MessageConfig $message
 * @property PageConfig $page
 * @property PermissionConfig $permission
 * @property RightToolbarConfig $right_toolbar
 * @property UploadConfig $upload
 * @property VendorConfig $vendor
 * @property TwigConfig $twig
 */
class SeeConfig
{
    /**
     * @var SeeConfig|null
     */
    protected static $instance = null;

    /**
     * @var array
     */
    protected $config = [];

    protected function __construct()
    {

    }

    protected function __clone()
    {

    }

    /**
     * @return SeeConfig
     */
    public static function instance(): SeeConfig
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
            // 加载默认配置
            self::$instance->loadDefaultConfig();
        }

        return self::$instance;
    }

    private function loadDefaultConfig()
    {
        $config = [];

        $files = glob(__DIR__ . '/../config/*.php');

        if ($files) {
            foreach ($files as $file) {
                $config = array_merge($config, include $file);
            }
        }

        $this->config = $config;
    }

    /**
     * @param $config
     * @return void
     */
    public function set($config)
    {
        if ($config && is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }
    }

    public function get($name = null): array
    {
        if (is_null($name)) {
            return $this->config;
        }

        return $this->config[$name] ?? [];
    }

    /**
     * 获取配置文件的值
     * @param $name
     * @return array|mixed
     */
    public function value($name)
    {
        return $this->config[$name] ?? [];
    }

    /**
     * @return bool
     */
    public function debug(): bool
    {
        $debug = boolval($this->config['debug'] ?? false);

        return $debug ?: false;
    }

    public function __get($name)
    {
        $namespace = Variable::pascal($name) . 'Config';
        $class = 'seecms\\lib\\config\\' . $namespace;
        if (class_exists($class)) {
            return new $class($this->config[$name] ?? []);
        }
        return null;
    }
}